﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using PremisPublisher;
using PremisPublisher.Common;
using PremisPublisher.Messages;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace PremisPublisher.ViewModel
{
    /*
     本项目日志显示窗体
     * 
     * 作者：张鹏
     * 日期：2016.5
     
     */

    public class LogViewModel : ViewModelBase
    {

        private string currentOperation;

        public string CurrentOperation
        {
            get { return currentOperation; }
            set { currentOperation = value; RaisePropertyChanged("CurrentOperation"); }
        }


        private ObservableCollection<string> _logContent;

        /// <summary>
        /// 日志
        /// </summary>
        public ObservableCollection<string> LogContent
        {
            get { return _logContent; }
            set
            {
                _logContent = value;
                RaisePropertyChanged("LogContent");
            }
        }

        private RelayCommand _clearContentCommand;

        public RelayCommand ClearContentCommand
        {
            get
            {
                return _clearContentCommand ??
                    (
                        _clearContentCommand = new RelayCommand(() =>
                        {
                            LogContent.Clear();
                        })
                    );

            }
        }


        private RelayCommand _saveContentCommand;
        public RelayCommand SaveContentCommand
        {
            get
            {
                return _saveContentCommand ??
                    (
                        _saveContentCommand = new RelayCommand(() => {
                            System.Windows.Forms.SaveFileDialog d = new System.Windows.Forms.SaveFileDialog();
                            d.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
                            d.DefaultExt = "*.log";
                            if (d.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                System.IO.File.WriteAllText(d.FileName, string.Join(Environment.NewLine, LogContent));
                            }
                        })
                    );
            }
        }


        public LogViewModel()
        {
            LogContent = new ObservableCollection<string>();
            Messenger.Default.Register<PublishLogMessage>(this, AddLogLine);
            Messenger.Default.Register<SetLogCurrentOperationMessage>(this, msg =>
            {
                this.CurrentOperation = msg.Message;
            });
        }

        private void AddLogLine(PublishLogMessage obj)
        {
            DispatchService.Invoke(() =>
            {
                LogContent.Add(obj.Message);
            });
        }
    }
}
